<?php

namespace app\index\controller;

use think\Controller;
use think\Exception;
use think\Request;

class User extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    //注册模块
    public function register()
    {
        if (\request()->isPost()) {
            $data = input('post.');
            if (!captcha_check($data['verifycode'])) {
                $this->error('验证码不正确');
            }
            $validate = validate('User');
            if (!$validate->scene('add')->check($data)) {
                $this->error($validate->getError());
            }
            $res = model('user')->add($data);
            if (!$res) {
                $this->error('注册失败');
            }
            $this->success('注册成功', url('/'));
        }
        return $this->fetch();
    }

    public function login()
    {
        //获取session信息
        $o2o_user = session('o2o_user', '', 'o2o');
        if ($o2o_user) {
            $this->redirect(url('/'));
        }
        if (\request()->isPost()) {
            $data = input('post.');
            if ($data['username'] == '') {
                $this->error('用户名不能为空');
            }
            if ($data['password'] == '') {
                $this->error('密码不能为空');
            }
            try {
                $res = model('user')->getUserByUsername($data['username']);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if (!$res || $res->status != 1) {
                $this->error('用户名不存在');
            }
            if ($res['password'] != MD5($data['password'] . $res['code'])) {
                $this->error('密码错误');
            }
            $date = date('Y-m-d H:i:s', time());
            model('user')->updateById(['last_login_time' => $date], $res->id);
            session('o2o_user', $res, 'o2o');
            $this->success('登录成功', url('index/index'));
        }
        return $this->fetch();
    }

    //登出
    public function logout()
    {
        //清空session
        session(null, 'o2o');
        $this->redirect(url('user/login'));
    }
}
